import React, {useEffect, useState} from 'react'
import {Editor} from 'react-draft-wysiwyg'
import {convertToRaw, ContentState, EditorState} from 'draft-js'
import draftToHtml from 'draftjs-to-html'
import htmlToDraft from 'html-to-draftjs';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css'

export default function NewsEditor(props) {
  const [editorState, setEditorState] = useState('')
  useEffect(() => {
    console.log(props.content)
    if (props.content === undefined) return
    const contentBlock = htmlToDraft(props.content);
    const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
    const editorState = EditorState.createWithContent(contentState)
    setEditorState(editorState)
  }, [props.content])
  const onEditorStateChange = (editorState) => {
    setEditorState(editorState)
  }  
  return (
    <div>
      <Editor
        editorState={editorState}
        toolbarClassName="toolbarClassName"
        wrapperClassName="wrapperClassName"
        editorClassName="editorClassName"
        onEditorStateChange={(editorState) => onEditorStateChange(editorState)}
        onBlur={() => {
          console.log(draftToHtml(convertToRaw(editorState.getCurrentContent())))
          props.getContent(draftToHtml(convertToRaw(editorState.getCurrentContent())))
        }}
      ></Editor>
    </div>
  )
}
